package com.vpen.client.scheduled;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 描述:定时任务；方法三 基于接口，也是单线程,优点，能动态修改间隔时间
 *
 * @author 韦鹏
 * @date 2022/11/25 11:40
 */
//@Data
@Slf4j
//@Component
//@PropertySource("classpath:task-config.properties")
//@EnableScheduling
public class ScheduleTask2 implements SchedulingConfigurer {


    /**
     * 可动态修改表达式
     */
    @Value("${printTime.cron}")
    private String cron;

    @Resource
    TaskScheduler taskScheduler;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {


        // 配置线程池
        taskRegistrar.setTaskScheduler(taskScheduler);


        //任务一
        taskRegistrar.addTriggerTask(() -> log.debug("方法二：任务1，执行异步任务......"), triggerContext -> {
            // 使用CronTrigger触发器，可动态修改cron表达式来操作循环规则
            CronTrigger cronTrigger = new CronTrigger(cron);
            return cronTrigger.nextExecutionTime(triggerContext);
        });
        // 任务二
        taskRegistrar.addCronTask(new CronTask(() -> log.debug("方法二: 任务2, 执行异步任务"), cron));


        // 任务三: 通过线程池直接提交
        ScheduledFuture<?> future = taskScheduler.schedule(() -> log.debug("方法二：任务3，执行异步任务......"), triggerContext -> {
            // 使用CronTrigger触发器，可动态修改cron表达式来操作循环规则
            CronTrigger cronTrigger = new CronTrigger(cron);
            return cronTrigger.nextExecutionTime(triggerContext);
        });

        // 停止定时任务
//        future.cancel(true);


    }


}
